<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2018/11/29
 * Time: 1:17 PM
 */

namespace app\purchase\model;

/**
 * Class GoodsSku
 * @package app\purchase\model
 * @OA\Schema(schema="GoodsSku", type="object", description="商品单品",
 *   @OA\Property(property="sku_id", description="单品ID", type="integer", format="int32", example=1, ),
 *   @OA\Property(property="sku_name", description="单品名称", type="string", example="蒙牛 纯牛奶" ),
 *   @OA\Property(property="sku_images", description="图片", type="array", @OA\Items(type="string"), ),
 *   @OA\Property(property="defaultImage", description="默认图片", type="string", ),
 *   @OA\Property(property="stock", description="单品库存", type="integer", format="int16", example=100, ),
 *   @OA\Property(property="price", description="单品价格", type="number", example=39.8, ),
 *   @OA\Property(property="specs", description="单品规格 键<规格名>:值<规格值>", type="object", example={1:2,2:3}),
 * )
 */
class GoodsSku extends \ShopModel
{
    protected $table = 'sh_goods_sku';

    use \app\purchase\traits\Goods;

    /**
     * 商品
     */
    public function goods()
    {
        return $this->hasMany('Goods', 'sku_id', 'sku_id')
            ->where([
                'is_delete' => 0,
                'is_on_sale' => 1,
            ])
            ->order('sort_order', 'desc');
    }

    /**
     * 默认商品
     */
    public function defaultGoods()
    {
        return $this->hasOne('Goods', 'goods_id', 'goods_id');
    }



    public function doWithSpecs()
    {
        $specsValues = [];
        $specsValuesIds = [];
        $count = count($this->specs);
        for ($i = 0; $i < $count; $i++) {
            $currentSpec = $this->specs[$i];
            // array_column($currentSpec->values, 'value_id')
            $currentSpec->valuesIds = array_map(function($value) {
                return $value->value_id;
            }, $currentSpec->values);
            $specsValues[] = $currentSpec->valuesIds;
            $specsValuesIds = array_merge($specsValuesIds, $currentSpec->valuesIds);
        }
        $this->specsValues = $specsValues;
        $this->specsValuesIds = $specsValuesIds;

        $count = count($this->goods);
        for ($i = 0; $i < $count; $i++) {
            $currentGoods = $this->goods[$i];
            $currentGoods->specsArray = array_values($currentGoods->goods_specs);
        }

        return $this;
    }
}